# 欢迎来到对抗路！！！
# 现在是北京时间: 2023/8/22 12:40
# Keep and you will win！！！
# ================= json 转换成python ==================
"""
json.loads(str)     # json 字符串转换成 python 数据
json.load(fp)       # json 文件转换成 python 数据
"""
import json

# 将json 字符串转换成python数据
json_str = '''[
  {
    "id": 1,
    "姓名": "张三",
    "年龄": 25,
    "邮箱": "zhangsan@example.com"
  },
  {
    "id": 2,
    "姓名": "李四",
    "年龄": 30,
    "邮箱": "lisi@example.com"
  },
  {
    "id": 3,
    "姓名": "王五",
    "年龄": 35,
    "邮箱": "wangwu@example.com"
  },
  {
    "id": 4,
    "姓名": "赵六",
    "年龄": 28,
    "邮箱": "zhaoliu@example.com"
  },
  {
    "id": 5,
    "姓名": "钱七",
    "年龄": 32,
    "邮箱": "qianqi@example.com"
  },
  {
    "id": 6,
    "姓名": "孙八",
    "年龄": 27,
    "邮箱": "sunba@example.com"
  },
  {
    "id": 7,
    "姓名": "周九",
    "年龄": 31,
    "邮箱": "zhoujiu@example.com"
  },
  {
    "id": 8,
    "姓名": "吴十",
    "年龄": 29,
    "邮箱": "wushi@example.com"
  },
  {
    "id": 9,
    "姓名": "郑十一",
    "年龄": 36,
    "邮箱": "zhengshiyi@example.com"
  },
  {
    "id": 10,
    "姓名": "王十二",
    "年龄": 33,
    "邮箱": "wangshier@example.com"
  }
]'''
rs = json.loads(json_str)
print(rs)
print(type(rs))     # <class 'list'>
print(type(rs[0]))  # <class 'dict'>

# 将json 文件转换成python数据
# with open('data.json', 'r', encoding='utf-8') as fp:
#     python_list = json.load(fp)
#     print(python_list)
#     print(type(python_list))        # <class 'list'>
#     print(type(python_list[0]))     # <class 'dict'>


# ==================== python 转换成json ================
"""
json.loads(str)         # 将 python 数据转换成json字符串
json.load(obj, fp)      # 将 python 数据写入到json 文件中
"""
json_str = '''[
  {
    "id": 1,
    "姓名": "张三",
    "年龄": 25,
    "邮箱": "zhangsan@example.com"
  },
  {
    "id": 2,
    "姓名": "李四",
    "年龄": 30,
    "邮箱": "lisi@example.com"
  },
  {
    "id": 3,
    "姓名": "王五",
    "年龄": 35,
    "邮箱": "wangwu@example.com"
  },
  {
    "id": 4,
    "姓名": "赵六",
    "年龄": 28,
    "邮箱": "zhaoliu@example.com"
  },
  {
    "id": 5,
    "姓名": "钱七",
    "年龄": 32,
    "邮箱": "qianqi@example.com"
  },
  {
    "id": 6,
    "姓名": "孙八",
    "年龄": 27,
    "邮箱": "sunba@example.com"
  },
  {
    "id": 7,
    "姓名": "周九",
    "年龄": 31,
    "邮箱": "zhoujiu@example.com"
  },
  {
    "id": 8,
    "姓名": "吴十",
    "年龄": 29,
    "邮箱": "wushi@example.com"
  },
  {
    "id": 9,
    "姓名": "郑十一",
    "年龄": 36,
    "邮箱": "zhengshiyi@example.com"
  },
  {
    "id": 10,
    "姓名": "王十二",
    "年龄": 33,
    "邮箱": "wangshier@example.com"
  }
]'''
rs = json.loads(json_str)   # python 数据
json_str1 = json.dumps(rs, ensure_ascii=False)  # json 数据
print(json_str1)
print(type(json_str1))      # <class 'str'>
print(type(json_str1[0]))   # <class 'str'>

# 将 python 数据转换成json 数据并写入到 json 文件中
with open('data_copy.json', 'w', encoding='utf-8') as fp:
    json.dump(rs, fp, ensure_ascii=False)
